package com.roger.homecenterscreen.ui.components

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CheckboxDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.roger.homecenterscreen.data.model.ContentData
import com.roger.homecenterscreen.data.model.ContentItem
import com.roger.homecenterscreen.data.model.ListItem
import kotlinx.coroutines.delay

@Composable
fun CustomContentDisplay(
    modifier: Modifier = Modifier,
    contentData: ContentData? = null,
    isLoading: Boolean = false,
    error: String? = null
) {
    var currentContent by remember { mutableStateOf(contentData ?: getMockContentData()) }
    
    // 当有新数据时更新当前内容
    LaunchedEffect(contentData) {
        contentData?.let { 
            currentContent = it
        }
    }
    
    LaunchedEffect(Unit) {
        while (true) {
            // 这里可以添加实际的API调用
            delay(currentContent.refreshInterval)
            // currentContent = fetchContentFromApi()
        }
    }
    
    Box(
        modifier = modifier.fillMaxSize()
    ) {
        // 背景图片
        AsyncImage(
            model = currentContent.backgroundImage.url,
            contentDescription = "背景图片",
            modifier = Modifier
                .fillMaxSize()
                .clip(RoundedCornerShape(8.dp)),
            contentScale = ContentScale.Crop,
            alpha = currentContent.backgroundImage.opacity
        )
        
        // 内容覆盖层
        Card(
            modifier = Modifier.fillMaxSize(),
            colors = CardDefaults.cardColors(
                containerColor = Color.White.copy(alpha = 0.95f)
            ),
            elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
        ) {
            when {
                isLoading -> {
                    Box(
                        modifier = Modifier.fillMaxSize(),
                        contentAlignment = Alignment.Center
                    ) {
                        Column(
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            CircularProgressIndicator()
                            Spacer(modifier = Modifier.height(16.dp))
                            Text(
                                text = "加载中...",
                                fontSize = 14.sp,
                                color = Color.Gray
                            )
                        }
                    }
                }
                error != null -> {
                    Box(
                        modifier = Modifier.fillMaxSize(),
                        contentAlignment = Alignment.Center
                    ) {
                        Column(
                            horizontalAlignment = Alignment.CenterHorizontally,
                            modifier = Modifier.padding(16.dp)
                        ) {
                            Text(
                                text = "❌",
                                fontSize = 48.sp
                            )
                            Spacer(modifier = Modifier.height(16.dp))
                            Text(
                                text = "加载失败",
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Bold,
                                color = Color.Black
                            )
                            Spacer(modifier = Modifier.height(8.dp))
                            Text(
                                text = error,
                                fontSize = 12.sp,
                                color = Color.Gray,
                                textAlign = TextAlign.Center
                            )
                        }
                    }
                }
                else -> {
                    LazyColumn(
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(16.dp),
                        verticalArrangement = Arrangement.spacedBy(16.dp)
                    ) {
                        items(currentContent.content.items) { item ->
                            when (item.type) {
                                "list" -> ListContentItem(item)
                                "text" -> TextContentItem(item)
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun CustomContentDisplay(
    modifier: Modifier = Modifier,
    wavFile: java.io.File?
) {
    val context = androidx.compose.ui.platform.LocalContext.current
    var player by remember(wavFile) { mutableStateOf<android.media.MediaPlayer?>(null) }
    var duration by remember(wavFile) { mutableStateOf(0) }
    var position by remember(wavFile) { mutableStateOf(0f) }
    var isPlaying by remember(wavFile) { mutableStateOf(false) }
    var saveMsg by remember(wavFile) { mutableStateOf<String?>(null) }

    androidx.compose.runtime.DisposableEffect(wavFile) {
        if (wavFile != null) {
            val p = android.media.MediaPlayer()
            try {
                p.setDataSource(wavFile.absolutePath)
                p.prepare()
                player = p
                duration = p.duration
                position = 0f
                isPlaying = false
            } catch (_: Exception) {
                player = null
                duration = 0
                position = 0f
                isPlaying = false
            }
        }
        onDispose {
            try { player?.stop() } catch (_: Exception) {}
            try { player?.release() } catch (_: Exception) {}
            player = null
        }
    }

    LaunchedEffect(isPlaying, player) {
        while (isPlaying && player != null) {
            try { position = player!!.currentPosition.toFloat() } catch (_: Exception) {}
            kotlinx.coroutines.delay(200)
        }
    }

    Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
        androidx.compose.material3.Card(
            modifier = Modifier.fillMaxWidth().padding(16.dp),
            colors = androidx.compose.material3.CardDefaults.cardColors(containerColor = Color.White.copy(alpha = 0.95f)),
            elevation = androidx.compose.material3.CardDefaults.cardElevation(defaultElevation = 4.dp)
        ) {
            Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
                androidx.compose.material3.Text(text = "声纹WAV试听", fontSize = 18.sp, color = Color.Black)
                Spacer(modifier = androidx.compose.ui.Modifier.height(12.dp))
                if (wavFile == null) {
                    androidx.compose.material3.Text(text = "暂无声纹音频", fontSize = 14.sp, color = Color.Gray)
                } else {
                    androidx.compose.material3.Text(text = wavFile.name, fontSize = 14.sp, color = Color.DarkGray)
                    Spacer(modifier = androidx.compose.ui.Modifier.height(12.dp))
                    androidx.compose.material3.Slider(
                        value = if (duration > 0) position.coerceIn(0f, duration.toFloat()) else 0f,
                        onValueChange = { v ->
                            position = v
                            try { player?.seekTo(v.toInt()) } catch (_: Exception) {}
                        },
                        valueRange = 0f..(duration.coerceAtLeast(1)).toFloat()
                    )
                    Spacer(modifier = androidx.compose.ui.Modifier.height(12.dp))
                    androidx.compose.foundation.layout.Row {
                        androidx.compose.material3.Button(onClick = {
                            try { player?.start(); isPlaying = true } catch (_: Exception) {}
                        }, enabled = !isPlaying) { androidx.compose.material3.Text("播放") }
                        Spacer(modifier = Modifier.width(8.dp))
                        androidx.compose.material3.Button(onClick = {
                            try { player?.pause(); isPlaying = false } catch (_: Exception) {}
                        }, enabled = isPlaying) { androidx.compose.material3.Text("暂停") }
                        Spacer(modifier = Modifier.width(8.dp))
                        androidx.compose.material3.Button(onClick = {
                            try { player?.pause(); player?.seekTo(0); isPlaying = false; position = 0f } catch (_: Exception) {}
                        }) { androidx.compose.material3.Text("停止") }
                    }
                    Spacer(modifier = androidx.compose.ui.Modifier.height(12.dp))
                    androidx.compose.material3.Button(onClick = {
                        if (wavFile != null) {
                            saveMsg = saveWavAs(context, wavFile)
                        }
                    }) { androidx.compose.material3.Text("另存为") }
                    Spacer(modifier = androidx.compose.ui.Modifier.height(8.dp))
                    androidx.compose.material3.Text(text = "时长: ${duration}ms  进度: ${position.toInt()}ms", fontSize = 12.sp, color = Color.Gray)
                    if (saveMsg != null) {
                        Spacer(modifier = androidx.compose.ui.Modifier.height(4.dp))
                        androidx.compose.material3.Text(text = saveMsg!!, fontSize = 12.sp, color = Color.DarkGray)
                    }
                }
            }
        }
    }
}

private fun saveWavAs(context: android.content.Context, src: java.io.File): String? {
    return try {
        val name = "voiceprint_${System.currentTimeMillis()}.wav"
        val values = android.content.ContentValues()
        values.put(android.provider.MediaStore.MediaColumns.DISPLAY_NAME, name)
        values.put(android.provider.MediaStore.MediaColumns.MIME_TYPE, "audio/wav")
        values.put(android.provider.MediaStore.MediaColumns.RELATIVE_PATH, "Download/HomeCenterScreen")
        val uri = context.contentResolver.insert(android.provider.MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)
        if (uri != null) {
            context.contentResolver.openOutputStream(uri)?.use { out ->
                java.io.FileInputStream(src).use { input ->
                    input.copyTo(out)
                }
            }
            "已保存到 下载/HomeCenterScreen/$name"
        } else {
            val dir = com.roger.homecenterscreen.voice.VoiceStorageHelper.getVoiceRecordDir(context)
            val dst = java.io.File(dir, "saved_${System.currentTimeMillis()}.wav")
            src.copyTo(dst, overwrite = false)
            "已保存到 ${dst.absolutePath}"
        }
    } catch (e: Exception) {
        "保存失败: ${e.message}"
    }
}

@Composable
private fun ListContentItem(contentItem: ContentItem) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = Color.White.copy(alpha = 0.9f)
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Text(
                text = contentItem.title,
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold,
                color = Color.Black
            )
            
            Spacer(modifier = Modifier.height(12.dp))
            
            contentItem.items?.forEach { listItem ->
                ListItemComponent(listItem)
                Spacer(modifier = Modifier.height(8.dp))
            }
        }
    }
}

@Composable
private fun ListItemComponent(listItem: ListItem) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Checkbox(
            checked = listItem.completed,
            onCheckedChange = { /* 这里可以添加状态更新逻辑 */ },
            colors = CheckboxDefaults.colors(
                checkedColor = getPriorityColor(listItem.priority),
                uncheckedColor = Color.Gray
            )
        )
        
        Spacer(modifier = Modifier.width(8.dp))
        
        Text(
            text = listItem.text,
            fontSize = 14.sp,
            color = if (listItem.completed) Color.Gray else Color.Black,
            modifier = Modifier.weight(1f)
        )
        
        // 优先级指示器
        Box(
            modifier = Modifier
                .size(8.dp)
                .background(
                    getPriorityColor(listItem.priority),
                    CircleShape
                )
        )
    }
}

@Composable
private fun TextContentItem(contentItem: ContentItem) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = Color.White.copy(alpha = 0.9f)
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Text(
                text = contentItem.title,
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold,
                color = Color.Black
            )
            
            Spacer(modifier = Modifier.height(12.dp))
            
            Text(
                text = contentItem.content ?: "",
                fontSize = 14.sp,
                lineHeight = 20.sp,
                color = Color.DarkGray,
                textAlign = TextAlign.Justify
            )
        }
    }
}

private fun getPriorityColor(priority: String): Color {
    return when (priority) {
        "high" -> Color(0xFFF44336)    // 红色
        "medium" -> Color(0xFFFF9800)  // 橙色
        "low" -> Color(0xFF4CAF50)     // 绿色
        else -> Color.Gray
    }
}

// 模拟数据
private fun getMockContentData(): ContentData {
    return ContentData(
        backgroundImage = com.roger.homecenterscreen.data.model.BackgroundImage(
            url = "https://picsum.photos/800/600",
            opacity = 0.3f
        ),
        content = com.roger.homecenterscreen.data.model.Content(
            type = "mixed",
            items = listOf(
                ContentItem(
                    type = "list",
                    title = "今日待办",
                    items = listOf(
                        ListItem("1", "查看重要邮件", false, "high"),
                        ListItem("2", "准备项目会议", false, "high"),
                        ListItem("3", "完成月度报告", true, "medium"),
                        ListItem("4", "团队例会", false, "medium"),
                        ListItem("5", "更新项目文档", false, "low")
                    )
                ),
                ContentItem(
                    type = "text",
                    title = "每日提醒",
                    content = "今天天气不错，适合外出。下午3点有重要会议，请提前准备相关材料。记得多喝水，保持良好的工作状态。晚上8点有在线培训课程，不要忘记参加。"
                ),
                ContentItem(
                    type = "list",
                    title = "购物清单",
                    items = listOf(
                        ListItem("6", "牛奶 2L", false, "low"),
                        ListItem("7", "面包", true, "low"),
                        ListItem("8", "鸡蛋 1打", false, "low"),
                        ListItem("9", "苹果 2斤", false, "low")
                    )
                ),
                ContentItem(
                    type = "text",
                    title = "今日格言",
                    content = "成功不是终点，失败也不是末日，唯有继续前进的勇气才是最可贵的。今天也要加油！"
                )
            )
        ),
        refreshInterval = 300000L
    )
}